import React, { useEffect } from 'react'
import PropTypes from 'prop-types'
import { Row, Divider } from 'antd'
import CssDisplayer from '../../../../components/CssDisplayer'
import { userstyleList, agentstyleList, parentstyleList, hightlights } from './cssData'

function addHighlight(list, hightlight) {
  return list.map(it => {
    return {
      ...it,
      styles: it.styles.map(s => {
        return {
          ...s,
          disabled: ! hightlight || ! hightlight.includes(s.field)
        }
      })
    }
  });
}

function getChangedStyles (current, list) {
  if(current === 1) {
    return list.reduce((prev, next) => {
      return next.styles.reduce((p, n) => {
        if(!n.disabled) {
          p[n.field] = n.value;
        }
        return p;
      }, prev);
    }, {});
  }
  else if(current === 2) {
    return {
      'font-size': '30px'
    };
  }
  else if(current === 3) {
    return {
      'text-align': 'center'
    };
  }
  else if(current === 4) {
    return {
      'background': 'transparent'
    };
  }
}

export default function StyleSample(props) {
  let userstyles = addHighlight(userstyleList, hightlights[props.current]);
  let agentstyles = addHighlight(agentstyleList, hightlights[props.current]);
  let parentstyles = props.current === 3? addHighlight(parentstyleList, hightlights[props.current]): addHighlight(parentstyleList, []);

  const cur = props.current;

  useEffect(() => {
    const s1 = getChangedStyles(cur, userstyles);
    const s2 = getChangedStyles(cur, agentstyles);
    const s3 = getChangedStyles(cur, parentstyles);
    props.onChange({...s1, ...s2, ...s3});
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [cur])

  return (
    <Row>
      <Row className="style-sample">
        <Divider orientation="left">
          作者样式表
        </Divider>
        <CssDisplayer styles={ userstyles } current={props.current}/>
      </Row>
      <Row className="style-sample">
        <Divider orientation="left">
          浏览器默认样式表
        </Divider>
        <CssDisplayer styles={ agentstyles } current={props.current}/>
      </Row>
      <Row className="style-sample">
        <Divider orientation="left">
          祖先元素样式表
        </Divider>
        <CssDisplayer styles={ parentstyles } current={props.current}/>
      </Row>
    </Row>
  )
}

StyleSample.propTypes = {
  current: PropTypes.number.isRequired
};
